<?php

namespace Models;

use Phalcon\Db\RawValue;
use Phalcon\Mvc\Model\Validator\Email as EmailValidator;
use Phalcon\Mvc\Model\Validator\Uniqueness as UniquenessValidator;
use Phalcon\Mvc\Model\Validator\Uniqueness as Uniqueness;
use Phalcon\Mvc\Model\Validator\Numericality as Numericality;

class User extends BaseModel
{

    public function initialize()
    {
        $this->hasMany("uid", "Models\AppUser", "uid", array('alias' => 'AppUser'));
        $this->hasMany("uid", "Models\Record", "uid", array('alias' => 'Record'));
        $this->hasMany("uid", "Models\Accesstoken", "uid", array('alias' => 'Accesstoken'));
    }

    public function beforeValidationOnCreate()
    {
        if (!isset($this->up_uid) || !$this->up_uid) {
            $this->up_uid = new RawValue('default');
        }
//        if (!isset($this->status) || !$this->status) {
//            $this->status = new RawValue('default');
//        }
        if (!isset($this->credit) || !$this->credit) {
            $this->credit = new RawValue('default');
        }
        if (!isset($this->email) || !$this->email) {
            $this->email = new RawValue('default');
        }
    }

    public function beforeValidationOnUpdate()
    {
        if (!isset($this->up_uid) || !$this->up_uid) {
            $this->up_uid = new RawValue('default');
        }
//        if (!isset($this->status) || !$this->status) {
//            $this->status = new RawValue('default');
//        }
        if (!isset($this->credit) || !$this->credit) {
            $this->credit = new RawValue('default');
        }
        if (!isset($this->email) || !$this->email) {
            $this->email = new RawValue('default');
        }
    }

    public function validation()
    {
        $this->validate(new EmailValidator(array(
            'field' => 'email',
            'message' => '邮箱格式不正确'
        )));
        $this->validate(new Uniqueness(array(
            'field' => 'username',
              'message' => '用户名已存在',
        )));
        $this->validate(new Numericality(array(
        'field' => 'sum',
        'message' => '积分格式为数字',
    )));
        if ($this->validationHasFailed() == true) {
            return false;
        }
    }




    public function notSave()
    {
        //Obtain the flash service from the DI container
        $flash = $this->getDI()->getFlash();

        //Show validation messages
        foreach ($this->getMessages() as $message) {
            $flash->error($message);
        }
    }

}